import os
path="C:\\Users\\Administrator\\Desktop\\md-Blog\\md"

def delete_lines(filename, start, end):
    with open(filename, 'r') as f:
        lines = f.readlines()
    with open(filename, 'w') as f:
        for i, line in enumerate(lines):
            if i < start-1 or i >= end:
                f.write(line)

def modify_files(path):
    for file in os.listdir(path):
        if file.endswith(".md"):
            categroy=None
            print(file)
            with open(os.path.join(path, file), 'r+', encoding='utf-8') as f:
                lines = f.readlines()
                if len(lines) < 15:
                    continue
                index_list=[i for i in range(15) if '---' in lines[i]]
                print(index_list)
                #
                for i in range(15):
                    if 'category:' in lines[i]:
                        index_categroy = [i, i+1 ,i+2]
                # index_categroy= [i for i in range(15) if 'category:' in lines[i] and ('- ' in lines[i] or '- ' in lines[i+1]) ]

                for i in index_categroy:
                    if '- ' in lines[i]:
                        categroy = lines[i].strip().replace('-', '')
                        break
                    elif '- ' in lines[i + 1]:
                        categroy = lines[i + 1].strip().replace('-', '')
                        break
                    if '- ' not in lines[i] and '- ' not in lines[i+1]:
                        categroy = lines[i].strip().replace('category:', '').strip()
                        if categroy is None:
                            categroy = lines[i+1].strip()
                        break
                if categroy:
                    categroy = categroy.strip().replace('-','')
                    print(categroy)
                # 写文件
                f.seek(0)
                f.truncate()
                #f.writelines(lines[index_list[1]:])
                for line in lines[index_list[1]:]:
                    if '<!-- more -->' not in line:
                        f.write(line)

            if categroy and not os.path.exists(os.path.join(path, categroy)):
                os.mkdir(os.path.join(path, categroy))
            os.rename(os.path.join(path, file), os.path.join(path, categroy, file))

modify_files(path)

